import {
  Button,
  DatePicker,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  Select,
  TimePicker
} from "antd";
import { connect } from "dva";
import moment from "moment";
import React from "react";
import enums from "./enums";
import styles from "./index.less";
import { transferOption } from "@/utils/common";

const { Option } = Select;

// const toLine = (name) => {
//   return name.replace(/([A-Z])/g, "_$1").toLowerCase();
// };
const formatToHump = (value) => {
  return value.replace(/\_(\w)/g, (_, letter) => letter.toUpperCase())
}
@connect((state) => ({
  theme: state.theme,
  creditCar: state.creditCar,
  merchantsData: state.menu.merchantsData
}))
export default class AddModal extends React.PureComponent {
  state = {
    vin: "",
    creditType: undefined,
    financeBeginDate: undefined,
    financeTerm: undefined,
    repaymentStatus: enums.repaymentStatus.inPayment.value,
    orgId: undefined,
    overdueDate: undefined,
    submitBntLading: false,
    fieldAdd: [],
    filterAddValue: [
      "vin",
      "finance_begin_date",
      "finance_term",
      "company_name",
      "org_name",
      "repayment_status",
      "overdue_date",
      "credit_type",
    ],
    addValue: {},
  };

  componentDidMount() {
    const _fieldAdd = JSON.parse(JSON.stringify(this.props.fieldAdd));
    const _specialData = JSON.parse(JSON.stringify(this.props.specialData));
    this.setState({
      fieldAdd: _fieldAdd.map((i) => {
        const _c = _specialData.find((j) => j.column == i.column);
        if (_c) {
          return {
            ...i,
            ..._c,
          };
        }
        return i;
      }),
    });
  }

  handleSubmit = (msg) => {
    const { changeAddModalVisible, merchantsData } = this.props;
    const { vin, creditType, financeBeginDate, financeTerm, orgId, repaymentStatus, overdueDate } =
      this.state;

    let submitData = {};
    if (!vin.trim()) {
      message.error("车辆VIN码不能为空");
      return;
    } else {
      submitData.vin = vin;
    }
    if (merchantsData.type !== 1) {
      if (this.state.creditType == 2 && !financeBeginDate) {
        message.error("融资起始日不能为空");
        return;
      } else {
        submitData.financeBeginDate = moment(financeBeginDate).format("YYYY-MM-DD");
      }
      if (this.state.creditType == 2 && !financeTerm && financeTerm !== 0) {//授信类型为个人2，必填，授信类型3为1经销商，非必填不校验
        message.error("融资期限不能为空");
        return;
      } else {
        submitData.financeTerm = financeTerm;
      }
      if (!orgId) {
        message.error("车辆所属公司不能为空");
        return;
      } else {
        submitData.orgId = orgId;
      }
      if (!creditType) {
        message.error("授信类型不能为空");
        return;
      } else {
        submitData.creditType = creditType;
      }
      submitData.repaymentStatus = repaymentStatus;
      if (repaymentStatus === enums.repaymentStatus.overdue.value) {
        if (!overdueDate) {
          message.error("逾期起始日不能为空");
          return;
        } else {
          submitData.overdueDate = moment(overdueDate).format(
            "YYYY-MM-DD"
          );
        }
      }
      for (let k in this.state.addValue) {
        submitData[formatToHump(k)] = this.state.addValue[k]
      }
    }

    this.setState({
      submitBntLading: true,
    });
    this.props.dispatch({
      type: "creditCar/postObjWithRes",
      payload: {
        url: merchantsData.type !== 1 ? "/mscreditbusiness/vehicle/credit/add" : "/mscreditbusiness/vehicle/credit/relation/add",
        ...submitData,
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("添加成功");
          changeAddModalVisible(true);
        } else {
          // message.error(response.statusMessage);
        }
        this.setState({
          submitBntLading: false,
        });
      },
    });
  };

  handleRadioClick = (e) => {
    this.setState({
      radioValue: e.target.value,
    });
  };

  setAddValue = (value, i) => {
    const addValue = JSON.parse(JSON.stringify(this.state.addValue));
    addValue[i.column] = value;
    console.log(addValue);
    this.setState({
      addValue: addValue,
    });
  };

  render() {
    const {
      submitBntLading,
      vin,
      creditType,
      financeBeginDate,
      financeTerm,
      orgId,
      repaymentStatus,
      overdueDate,
    } = this.state;

    const { changeAddModalVisible, orgList, creditTypeOptions, merchantsData } = this.props;
    const disabledDate = (current) => {
      return current && (current < moment().year(1969).month(11).date(31) || current > moment().endOf("day"));
    };
    return (
      <Modal
        title="新增授信车辆"
        onCancel={() => changeAddModalVisible(false)}
        visible={true}
        footer={[
          <Button
            key="back"
            type="ghost"
            onClick={() => changeAddModalVisible(false)}
          >
            取 消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={submitBntLading}
            onClick={() => this.handleSubmit("submit")}
          >
            提 交
          </Button>,
        ]}
      >
        <div className={styles.addModal}>
          <div className={styles.publicItem}>
            <div className={styles.itemLeft}>
              <span>*</span>车辆VIN码 :
            </div>
            <div className={styles.itemRight}>
              <Input
                value={vin}
                placeholder={"请输入车辆vin码"}
                onChange={(e) => {
                  this.setState({
                    vin: e.target.value || "",
                  });
                }}
              />
            </div>
          </div>
          {
            merchantsData.type !== 1 ?
              <>

                <div className={styles.publicItem}>
                  <div className={styles.itemLeft}>
                    <span>*</span>授信类型 :
                  </div>
                  <div className={styles.itemRight}>
                    <Select
                      value={creditType}
                      placeholder={"请选择授信类型"}
                      onChange={(e) => {
                        this.setState({
                          creditType: e,
                        });
                      }}
                    >
                      {transferOption(creditTypeOptions, ["value", "label"])}
                    </Select>
                  </div>
                </div>
                <div className={styles.publicItem}>
                  <div className={styles.itemLeft}>
                    <span>*</span>车辆所属公司 :
                  </div>
                  <div className={styles.itemRight}>
                    <Select
                      value={orgId}
                      placeholder={"请选择车辆所属公司"}
                      onChange={(e) => {
                        this.setState({
                          orgId: e,
                        });
                      }}
                    >
                      {orgList.map((org) => {
                        return (
                          <Option key={org.sid} value={org.sid}>
                            {org.name}
                          </Option>
                        );
                      })}
                    </Select>
                  </div>
                </div>
                <div className={styles.publicItem}>
                  <div className={styles.itemLeft}>
                    {this.state.creditType == 2 ? (<span>*</span>) : null}
                    融资起始日 :
                  </div>
                  <div className={styles.itemRight}>
                    <DatePicker
                      value={financeBeginDate}
                      disabledDate={disabledDate}
                      onChange={(e) => {
                        this.setState({
                          financeBeginDate: e,
                        });
                      }}
                      placeholder={"请选择融资起始日"}
                    />
                  </div>
                </div>
                <div className={styles.publicItem}>
                  <div className={styles.itemLeft}>
                    {this.state.creditType == 2 ? (<span>*</span>) : null}
                    融资期限(月) :
                  </div>
                  <div className={styles.itemRight}>
                    <InputNumber
                      value={financeTerm}
                      min={0}
                      max={9999}
                      placeholder={"请输入融资期限(月)"}
                      onChange={(e) => {
                        this.setState({
                          financeTerm: e,
                        });
                      }}
                    />
                  </div>
                </div>
                <div className={styles.publicItem}>
                  <div className={styles.itemLeft}>
                    <span>*</span>还款状态 :
                  </div>
                  <div className={styles.itemRight}>
                    <Radio.Group
                      value={repaymentStatus}
                      onChange={(e) => {
                        this.setState({
                          repaymentStatus: e.target.value,
                          overdueDate: undefined,
                        });
                      }}
                    >
                      {enums.repaymentStatus.array.map((radio) => {
                        if (
                          radio.value === enums.repaymentStatus.inPayment.value ||
                          radio.value == enums.repaymentStatus.overdue.value
                        ) {
                          return (
                            <Radio key={radio.value} value={radio.value}>
                              {radio.label}
                            </Radio>
                          );
                        }
                      })}
                    </Radio.Group>
                  </div>
                </div>
                {repaymentStatus === enums.repaymentStatus.overdue.value ? (
                  <div className={styles.publicItem}>
                    <div className={styles.itemLeft}>
                      <span>*</span>逾期起始日 :
                    </div>
                    <div className={styles.itemRight}>
                      <DatePicker
                        // disabledDate={(current) => {
                        //   return current && current > moment().endOf("day");
                        // }}
                        value={overdueDate}
                        disabledDate={disabledDate}
                        placeholder={"请选择逾期起始日"}
                        onChange={(e) => {
                          this.setState({
                            overdueDate: e,
                          });
                        }}
                      />
                    </div>
                  </div>
                ) : null}
                {this.state.fieldAdd &&
                  this.state.fieldAdd
                    .filter((i) => !this.state.filterAddValue.includes(i.column))
                    .map((i) => {
                      const extra = i.extra;
                      return (
                        <div
                          className={styles.publicItem}
                          key={`addModal${i.column}`}
                        >
                          <div className={styles.itemLeft}>{i.name} :</div>
                          <div className={styles.itemRight}>
                            {i.type == "1" && (
                              <Input
                                style={{ width: 300 }}
                                placeholder="请输入"
                                value={this.state.addValue[i.column]}
                                onChange={(e) => {
                                  this.setAddValue(e.target.value, i);
                                }}
                              ></Input>
                            )}
                            {i.type == "2" && (
                              <Select
                                style={{ width: 300 }}
                                value={
                                  extra && typeof extra == "string" ?
                                    (JSON.parse(extra).selectType == "0" || JSON.parse(extra).selectType == "1") &&
                                    (JSON.parse(extra).selectType == "1"
                                      ? this.state.addValue[i.column]
                                        ? (this.state.addValue[i.column] || '').split(",")
                                        : undefined
                                      : this.state.addValue[i.column])
                                    : (extra.selectType == "0" || extra.selectType == "1") &&
                                    (extra.selectType == "1"
                                      ? this.state.addValue[i.column]
                                        ? (this.state.addValue[i.column] || '').split(",")
                                        : undefined
                                      : this.state.addValue[i.column])
                                }
                                placeholder="请选择"
                                mode={
                                  extra &&
                                    typeof extra == "string" ?
                                    (JSON.parse(extra).selectType == '1' ? "multiple" : "")
                                    : (extra.selectType == '1' ? "multiple" : "")
                                }
                                onChange={(e) => {
                                  this.setAddValue(Array.isArray(e) ? e.join(',') : e, i);
                                }}
                              >
                                {/* {JSON.parse(i.extra).optionList.map((i) => {
                              return (
                                <Option
                                  key={`${i.column}${i.value}`}
                                  value={i.value}
                                >
                                  {i.label}
                                </Option>
                              );
                            })} */}
                                {extra &&
                                  typeof extra !== "string" &&
                                  extra.optionList.map((i) => {
                                    return (
                                      <Option
                                        key={`${i.column}-select-${i.label}`}
                                        value={i.value}
                                      >
                                        {i.label}
                                      </Option>
                                    );
                                  })}
                                {extra &&
                                  typeof extra == "string" &&
                                  JSON.parse(extra).optionList &&
                                  JSON.parse(extra).optionList.map((i) => {
                                    return (
                                      <Option
                                        key={`${i.column}-select-${i}`}
                                        value={i}
                                      >
                                        {i}
                                      </Option>
                                    );
                                  })}
                              </Select>
                            )}
                            {i.type == "3" && (
                              <InputNumber
                                placeholder="请输入"
                                style={{ width: 300 }}
                                value={this.state.addValue[i.column]}
                                precision={extra ? (parseInt(extra) >= 4 ? 4 : parseInt(extra)) : 0}
                                max={100000000000}
                                min={-100000000000}
                                formatter={value => {
                                  return Math.abs(value) > 100000000000 ? (value < 0 ? -100000000000 : 100000000000) : value
                                }}
                                parser={value => {
                                  return Math.abs(value) > 100000000000 ? (value < 0 ? -100000000000 : 100000000000) : value
                                }}
                                onChange={(e) => {
                                  this.setAddValue(`${e}`, i);
                                }}
                              ></InputNumber>
                            )}
                            {i.type == "4" && (
                              <DatePicker
                                style={{ width: 300 }}
                                value={this.state.addValue[i.column] ? moment(this.state.addValue[i.column]) : undefined}
                                format="YYYY-MM-DD"
                                placeholder="请选择日期"
                                onChange={(e) => {
                                  this.setAddValue(moment(e).format("YYYY-MM-DD"), i);
                                }}
                              />
                            )}
                            {i.type == "5" && (
                              <TimePicker
                                style={{ width: 300 }}
                                value={this.state.addValue[i.column] ? moment(this.state.addValue[i.column], 'HH:mm:ss') : undefined}
                                format="HH:mm:ss"
                                placeholder="请选择时间"
                                onChange={(e, timeString) => {
                                  this.setAddValue(timeString, i);
                                }}
                              />
                            )}
                            {i.type == "6" && (
                              <DatePicker
                                style={{ width: 300 }}
                                value={this.state.addValue[i.column] ? moment(this.state.addValue[i.column]) : undefined}
                                format="YYYY-MM-DD HH:mm:ss"
                                showTime
                                placeholder="请选择日期"
                                onChange={(e) => {
                                  this.setAddValue(
                                    moment(e).format("YYYY-MM-DD HH:mm:ss"),
                                    i
                                  );
                                }}
                              />
                            )}
                            {i.type == "7" && (
                              <Input
                                style={{ width: 300 }}
                                placeholder="请输入"
                                value={this.state.addValue[i.column]}
                                onChange={(e) => {
                                  this.setAddValue(e.target.value, i);
                                }}
                              ></Input>
                            )}
                          </div>
                        </div>
                      );
                    })}
              </> : null
          }

        </div>
      </Modal>
    );
  }
}
